
import baseUrl from "./baseUrl.js"
import store from "@/store";

export const myRequest = (options) => {
	
	let network = '', _url = `${baseUrl}${options.url}`
	
	// 检查网络是否正常
	uni.getNetworkType({
	    success: (res) => {
	        if (res.networkType != 'none') {
				network = true
			}else {
				uni.showToast({
					title: '暂无网络，请检查是否连接网络',
					icon: 'none'
				})
				network = false
			}
	    }
	});
	if (!network) return
	
	return new Promise((resolve, reject) => {
		
		// #ifdef H5
		_url = options.url
		// #endif
		
		let reqHeader = {
			'Authorization': uni.getStorageSync('TOKEN') || null,
			'Content-Type': 'application/json'
		}
		
		options.author ? delete reqHeader.Authorization : null;
		
		uni.request({
			url: _url,
			
			header: reqHeader,
			
			data: { input: options.data } || {},
			
			method: options.method || 'GET',	
					
			withCredentials: true,
			
			success: (res) => {
				// 登录失效
				if (res.data.code === 401) {
					uni.showToast({
						title: '登录失效，请重新登录',
						icon: 'none'
					})
					// 清空用户相关信息
					uni.removeStorageSync('TOKEN');
					uni.removeStorageSync('USER_ID');
					if (plus.os.name == 'Android') {
						this.$store.state.isSocketOpen = false;
						this.$keepAlive.stopKeepAlive();
					}
					store.commit('saveUser', null);
					// 跳至登录页
					store.dispatch('toLogin');
				}
				// 成功获取数据
				else if(res.data.code === 0) {
					resolve(res.data);
				}
				// 接口异常
				else {
					uni.showToast({
						title: res.data.message,
						icon: 'none'
					})
					resolve(res.data);
				}
			},
			
			fail: (err) => {
				uni.showToast({
					title: '系统繁忙，请稍后再试',
					icon: 'none'
				})
				reject(err)
			}
		})
	})
}